<style>
	.el-textarea__inner{
		min-height: 100px !important
	}
</style>

<template>
	<section>
			<el-row>
				<!--工具条-->
				<el-col :span="23" class="toolbar toolMarginTop" id="serachId">
					<el-form :inline="true" :model="filters">
						<el-button @click="ApplicationType" type="primary" size="small" style="float:left;">新增分类</el-button>
						<el-form-item style="float:right">
							<el-button type="primary" v-on:click="getList" size="small">查询</el-button>
						</el-form-item>
						<el-form-item style="float:right">
							<el-input v-model="filters.className" placeholder="请输入分类名称" size="small" @keyup.enter.native="searchEnterFun"></el-input>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<el-col :span="23" >
				<!--列表-->
				<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
					<el-table-column type="index" label="序号" width="60">
					</el-table-column>
					<el-table-column prop="className" label="分类名称">
					</el-table-column>
					<el-table-column prop="sort" label="排序">
					</el-table-column>
					<el-table-column prop="creater" label="创建人">
					</el-table-column>
					<el-table-column prop="createDate" label="创建时间" :formatter="formatCreateDate">
					</el-table-column>
					<el-table-column label="操作" min-width="150" align='center'>
						<template slot-scope="scope">
							<el-button type="text" size="mini" @click="ApplicationTypeEdit(scope.$index, scope.row)">编辑</el-button>
							<el-button type="text" size="mini" @click="ApplicationTypeDelete(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!--工具条-->
				<el-col :span="24" class="toolbar">
					<el-pagination layout="total, prev, pager, next, jumper" @current-change="handleCurrentPageChange"
									:current-page="pageNum" :page-size="pageSize" :total="total">
					</el-pagination>
				</el-col>
			</el-col>

			<!--编辑界面-->
			<Modal v-model="editFormVisible" title="分类编辑" width='50%'>
				<el-card>
				<el-form :model="editForm" label-width="120px" :rules="rules" ref="editForm">
					<el-form-item label="分类图标" prop="fltb">
						<el-upload
								:data="paramData"
								class="upload-demo"
								ref="upload"
								:action="uploadUrl"
								:on-remove="handleRemove"
								:before-remove="beforeRemove"
								:file-list="fileList"
								:limit="1"
								:on-exceed="handleExceed"
								:auto-upload="true"
								:on-success="uploadSuccess">
							<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
						</el-upload>
						<div id = "editId">
						</div>
					</el-form-item>
					<el-form-item label="分类名称" prop="className">
						<el-input v-model="editForm.className" placeholder="不超过20个汉字" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="排序">
						<el-input v-model="editForm.sort"></el-input>
					</el-form-item>
					<el-form-item label="分类描述">
						<el-input type="textarea" v-model="editForm.remark"></el-input>
					</el-form-item>
				</el-form>
				</el-card>
				<div slot="footer" class="dialog-footer">
					<el-button @click.native="editFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
				</div>
			</Modal>

			<!--新增界面-->
			<Modal v-model="addFormVisible" title="新增分类" width='50%'>
				<el-card>
				<el-form :model="addForm" label-width="120px" :rules="rules" ref="addForm">
					<el-form-item label="分类图标"  prop="fltb">
						<el-upload
								:data="paramData"
								class="upload-demo"
								ref="upload"
								:action="uploadUrl"
								:on-remove="handleRemove"
								:before-remove="beforeRemove"
								:file-list="fileList"
								:limit="1"
								:on-exceed="handleExceed"
								:auto-upload="true"
								:on-success="uploadSuccess"
								list-type="picture">
							<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
							 <div slot="tip" class="el-upload__tip"></div>
						</el-upload>
						<div id = "addId">
						</div>
					</el-form-item>
					<el-form-item label="分类名称" prop="className">
						<el-input v-model="addForm.className" placeholder="不超过20个汉字" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="排序">
						<el-input v-model="addForm.sort" id="myId" @change="inputChange('sort','myId',addForm)"></el-input>
					</el-form-item>
					<el-form-item label="分类描述">
						<el-input type="textarea" v-model="addForm.remark"></el-input>
					</el-form-item>
				</el-form>
				</el-card>
				<div slot="footer" class="dialog-footer">
					<el-button @click.native="addFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="addSubmit" :loading="addLoading" >提交</el-button>
				</div>
			</Modal>
	</section>
</template>

<script>
	import utils from '../../api/utils'
	import  checks  from '../../api/checks'
	import { getApplicationTypeList,addApplicationType,editApplicationType,deleteApplicationType,getMarketList } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					className: ''
				},
				tableData: [],
				total: 0,
				pageNum: 1,
				pageSize:10,
				listLoading: false,
				sels: [],//列表选中列
				market:[],//所有市场
				superClassList:[],//所有分类

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				//编辑界面数据
				editForm: {
					className : '',
					superClass : '',
					logo : '',
					isShow : -1,
					marketCode : '',
					sort : 100,
					remark : ''
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				rules: {
					className: [
						{ required: true, message: '请输入分类名称', trigger: 'blur' }
					],
					fltb: [
						{ required: true, message: '请上传图标', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
					className : '',
					superClass : '',
					logo : '',
					isShow : -1,
					marketCode : '',
					sort : 100,
					remark : '',
					
				},
				defaultProps: {
					label: 'marketName',
					isLeaf: 'leaf',
				},
				fileList: [],
				paramData:{sys:1,module:3,keyId:""},
				fileUrl:'',

				addOrEdit:0,
				uploadUrl:'',
			}
		},
		methods: {
			formatIsShow: function (row, column) {
				return row.isShow == 1 ? '是' : row.isShow == 0 ? '否' : '未知';
			},
			formatCreateDate: function (row, column) {
				return row.createDate = (!row.createDate || row.createDate == '') ? '' : checks.formatDate(new Date(row.createDate), 'yyyy-MM-dd hh:mm');//时间显示为时分
			},
			formatUpdateDate: function (row, column) {
				return row.updateDate = (!row.updateDate || row.updateDate == '') ? '' : checks.formatDate(new Date(row.updateDate), 'yyyy-MM-dd hh:mm');//时间显示为时分
			},
			handleCurrentPageChange: function (pageNum) {// 翻页动作
                this.pageNum = pageNum;
                this.getList();// 翻页后刷新页面数据
			},

			inputChange: function (name,id,form) {
				checks.checkNum(name,id,form,0,this);
			},
			//实现回车键搜索功能
			searchEnterFun:function(e){
				this.getList();
            },
			//获取列表
			getList() {
				let params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					className: this.filters.className,
					// marketCodeList:this.$refs.tree.getCheckedKeys()
				};
				this.listLoading = true;
				//NProgress.start();
				getApplicationTypeList(params).then(function(result){
					this.tableData = result.data.list;
					this.pageNum = result.data.pageNum;
					this.pageSize = result.data.pageSize;
					this.total = result.data.total;
					this.listLoading = false;
				}.bind(this)).catch(function (error) {
					this.listLoading = false;
					console.log(error);
				}.bind(this));
			},
			//删除
			ApplicationTypeDelete: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let params = {classCode:row.classCode};
					deleteApplicationType(params).then((res) => {
						if(res.code == 'B100001'){
							this.$message({
								message: "应用分类正在使用，不允许删除！",
								type: 'info'
							});
						}else{
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.listLoading = false;
						this.getList();
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					}); 
				});
			},	
			//显示编辑界面
			ApplicationTypeEdit: function (index, row) {
				this.editFormVisible = true;
				this.getmarketList();
				// this.getAllSuperClassList(row.classCode);
				let testId = document.getElementById("testId");
				if(testId != undefined){
					document.getElementById("editId").removeChild(testId);
				}
				this.addOrEdit = 1;
				if(row.logo != null && row.logo != ""){
					let div = document.createElement('div');
					let html = '<img width="100%" src="'+row.logo+'" alt="" style="width: 100px;height: 100px;" class="test">';
					div.innerHTML = html;
					div.id = 'testId';
					document.getElementById("editId").appendChild(div);
				}
				this.fileUrl = row.logo;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			ApplicationType: function () {
				let testId = document.getElementById("testId");
				if(testId != undefined){
					document.getElementById("addId").removeChild(testId);
				}
				this.fileUrl = '';
				this.fileList = [];
				this.addOrEdit = 0;
				this.addForm = {
					className : '',
					superClass : '',
					logo : '',
					isShow : 1,
					marketCode : '',
					sort : 100,
					remark : ''
				};
				this.getmarketList();
				// this.getAllSuperClassList('no');
				this.addFormVisible = true;
			},
			//查所有市场
			getmarketList() {
				let params = {
					pageNum: 1,
					pageSize: 10000,
					marketName: ''
				};
				getMarketList(params).then(function(result){
					this.market = result.data.list;
				}.bind(this)).catch(function (error) {
					console.log(error);
				}.bind(this));
			},
			//查所有分类
			getAllSuperClassList(classCode) {
				if(classCode == 'no'){
					classCode = '';
				}
				let params = {
					pageNum: 1,
					pageSize: 10000,
					notSelf:classCode
				};
				//NProgress.start();
				getApplicationTypeList(params).then(function(result){
					this.superClassList = result.data.list;
				}.bind(this)).catch(function (error) {
					console.log(error);
				}.bind(this));
			},
			//编辑
			editSubmit: function () {
				if(this.editForm.className.length > 20){
					this.$message({
						message: '分类名称不超过20个汉字',
						type: 'info'
					});
					return;
				}
				this.addForm.fltb = '' // todo 作为不能填空的作用
				if(this.fileUrl.length>0){
					this.editForm.fltb = 'true'
				}
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let params = Object.assign({}, this.editForm);
							params.createDate = Date.parse(new Date(params.createDate));
							if(params.updateDate != ''){
								params.updateDate = Date.parse(new Date(params.updateDate));
							}
							params.logo = this.fileUrl;
							editApplicationType	(params).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getList();
							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				if(this.addForm.className.length > 20){
					this.$message({
						message: '分类名称不超过20个汉字',
						type: 'info'
					});
					return;
				}
				this.addForm.fltb = '' // todo 作为不能填空的作用
				if(this.fileUrl.length>0){
					this.addForm.fltb = 'true'
				}
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let params = Object.assign({}, this.addForm);
							params._logo = this.fileUrl;
							//params.file = document.getElementById('file').files;
							addApplicationType(params).then((res) => {
								if(res.code == 'B100001'){
									this.$message({
										message: "已存在分类！",
										type: 'info'
									});
								}else{
									//NProgress.done();
									this.$message({
										message: '提交成功',
										type: 'success'
									});
								}
								this.addLoading = false;
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getList();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			},
			toGetList:function(){
				this.getList();
			},
			loadData(node,resolve){
				let rootName = '市场';
				if(node.level ===0){
					resolve([{marketName:rootName}]);
					return;
				}

				if(node.data.marketName===rootName){
					let params ={
						marketName:'',
					}
					getMarketList(params).
					then(res => {
						res.data.list.map(item=>{item.leaf=true;});
						resolve(res.data.list);
					}).catch(function (error) {
						this.$message.warning('系统异常 ');
					});
					return;
				}
				return;
			},
			submitUpload() {
                this.paramData.keyId="9999999999999999999999";
                this.$refs.upload.submit();
            },
            handleRemove(file, fileList) {
				this.fileUrl = '';
				let testId = document.getElementById("testId");
				if(this.addOrEdit === 0){
					document.getElementById("addId").removeChild(testId);
				}
				if(this.addOrEdit === 1){
					document.getElementById("editId").removeChild(testId);
				}
                console.log("移除文件");
                console.log(file, fileList);
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }？`);
            },
            handlePreview(file) {
                console.log("点击文件");
                console.log(file);
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            uploadSuccess(response, file, fileList){
				let testId = document.getElementById("testId");
				this.fileUrl = response.data.fileUri;
				let div = document.createElement('div');
				let html = '<img width="100%" src="'+this.fileUrl+'" alt="" style="width: 100px;height: 100px;" class="test">';
				div.innerHTML = html;
				div.id = 'testId';
				if(this.addOrEdit === 0){
					if(testId != undefined){
						document.getElementById("addId").removeChild(testId);
					}
					document.getElementById("addId").appendChild(div);
				}
				if(this.addOrEdit === 1){
					if(testId != undefined){
						document.getElementById("editId").removeChild(testId);
					}
					document.getElementById("editId").appendChild(div);
				}
                console.log(response)
            },
		},
		mounted() {
			this.getList();
			this.uploadUrl = utils.uploadUrl(); //设置图片上传地址
		},
		created(){
		}
	}

</script>